<template>
  <view>
    <view class="page-top-place"></view>
    <view class="page-content">
      <view class="content-card-title am-flex-row-center">商品信息</view>
      <view>
        <view class="company-section">
          <view class="products-wrap">
            <view
              class="goods-item"
              v-for="list in orderDetails.orderDetailVOList"
              :key="list.cartId"
            >
              <view class="goods-cover">
                <image
                  :src="
                    $imageCutting(list.productVO.banner.split(',')[0], 120, 120)
                  "
                  mode="aspectFill"
                  class="goods-cover-img am-wh-100 am-block"
                ></image>
              </view>
              <view class="goods-con">
                <view class="goods-name-wrap">
                  <text class="goods-name am-line-clamp-two am-text-break">{{
                    list.productVO.name
                  }}</text>
                  <text class="specStyle">{{ list.productVO.spec }}</text>
                </view>
                <view>
                  <view v-if="orderDetails.originalPrice" class=" original-price">
                    <text >￥</text>
                    <text>{{ orderDetails.originalPrice }}元</text>
                  </view>
                </view>
                <view class="am-flex-rc-between goods-price-wrap">
                  <view class="goods-price">
                    <text class="goods-price-unit">￥</text>
                    <text>{{ list.orderPrice }}元</text>
                  </view>
                  <view class="goods-price-num">x{{ list.num }}</view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
      <u-cell-group :border="false"
        ><u-cell-item
          title="运费"
          :hover-class="none"
          :value="freightShow"
          :arrow="false"
        ></u-cell-item
      ></u-cell-group>
      <view class="content-card-title am-flex-row-center">
        收货信息
        <text class="tip">（您可以选择我的地址或直接输入客户信息）</text>
      </view>
      <u-cell-group :border="false">
        <u-cell-item
          title="我的地址"
          value="请选择"
          @click="chooseCustomer"
        ></u-cell-item>

        <!-- <view class="" slot="label">
            <view class="receiving-address">
              <u-input
                type="textarea"
                v-model="receivingAddress"
                :height="250"
                :maxlength="100"
                placeholder="粘贴或输入文本，点击“识别”自动识别联系、收件人、联系电话、收货地"
                :custom-style="receivingAddressSty"
              ></u-input>
              <view
                class="receiving-address__btn"
                hover-class="receiving-address__btn-hover"
                @click.stop="addressTextGet"
                >识别</view
              >
            </view>
          </view> -->

        <u-cell-item title="收货人" :arrow="false">
          <view class="f-cell-item">
            <view class="f-cell-item-input"
              ><u-input
                v-model="consignee"
                input-align="right"
                placeholder="请输入"
                :maxlength="20"
              ></u-input
            ></view>
          </view>
        </u-cell-item>
        <u-cell-item title="收货电话" :arrow="false">
          <view class="f-cell-item">
            <view class="f-cell-item-input"
              ><u-input
                v-model="receivingPhone"
                input-align="right"
                placeholder="请输入"
                :maxlength="11"
              ></u-input
            ></view>
          </view>
        </u-cell-item>
        <u-cell-item title="省-市-区" :arrow="false">
          <view class="f-cell-item">
            <view class="f-cell-item-input">
              <div @click="showCoC" v-if="status === 0">
                <view class="" v-if="!regionStr">
                  请选择
                  <u-icon name="arrow-right"></u-icon>
                </view>
                <view>{{ regionStr }}</view>
              </div>
              <co-city-picker
                v-if="status === 0"
                :value="addressValue"
                :selectShow="show"
                @confirm="addressPickerChange"
                @cancel="selectCancel"
              >
              </co-city-picker>
              <co-address-picker
                v-if="status === -1"
                @change="addressPickerChange"
                :value="addressValue"
              >
                <view class="" v-show="!regionStr">
                  请选择
                  <u-icon name="arrow-right"></u-icon>
                </view>
                <view>{{ regionStr }}</view>
              </co-address-picker>
              <picker mode="region" @change="regionChange"></picker>
            </view>
          </view>
        </u-cell-item>
        <view @click="toPosition"
          ><u-cell-item title="详细地址" :arrow="false">
            <view class="f-cell-item">
              <view class="f-cell-item-input">
                <input
                  v-model="detailedAddress"
                  input-align="right"
                  placeholder="请选择详细地址"
                  :maxlength="100"
                />
              </view>
            </view> </u-cell-item
        ></view>
      </u-cell-group>
      <view class="f-cell-text">
        <view>备注</view>
        <view class="f-cell-item">
          <view class="f-cell-item-input"
            ><u-field
              v-model="remark"
              input-align="right"
              placeholder="请输入"
              type="textarea"
              :maxlength="100"
            ></u-field
          ></view>
        </view>
      </view>
    </view>
    <view class="err-tip" v-if="isPinkage"
      >当前收货地址卖家不支持配送，请修改收货地</view
    >
    <!-- <payment-method ref="paymentRef" @payFail="payFailCb" @paySuccess="paySuccessCb" :scene="payScene"></payment-method> -->
    <view class="footer-bar am-flex-rc-between">
      <button
        class="u-reset-button submit-button"
        :class="{ 'disable-btn': !getDetailsSuccess }"
        hover-class="submit-button-hover"
        @click="submitOrder"
        :loading="submitOrderLoading"
        :disabled="!getDetailsSuccess"
      >
        提交
      </button>
    </view>
    <view class="footer-bar-place"></view>
    <u-modal
      v-model="modalShow"
      titl="温馨提示"
      :content="
        flag === 3
          ? '您修改后地址的省份，运费与当前订单的运费不符~ 请先取消订单，进行重新下单操作！'
          : '您修改后的地址暂时不支持配送，请重新修改'
      "
    ></u-modal>
  </view>
</template>

<script>
import { apiAddressGet } from '@/api/common.js'
import { apiOrderDetails, apiUpdateOrder } from '@/api/order'
import {
  CHOOSE_RECEIVING_ADDRESS,
  UPDATE_ORDER_DETAILS
} from '@/types/globalEventName'
export default {
  data() {
    return {
      flag: 1,
      modalShow: false,
      isFreight: true, // 是否包邮
      status: -1,
      show: false,
      receivingAddress: '', // 收货地址
      receivingAddressSty: {
        fontSize: '30rpx',
        color: '#333',
        lineHeight: '42rpx'
      },
      consignee: '', // 收货人
      receivingPhone: '', // 收货电话
      regionStr: '',
      detailedAddress: '', // 详细地址
      remark: '', // 备注
      pageQuery: {},
      addressCode: [],
      addressValue: [],
      submitOrderLoading: false,
      cartOrderData: [],
      goodsNum: 1,
      orderDetails: {
        orderDetailVOList: []
      },
      getDetailsSuccess: false,
      freight: null,
      isPinkage: false,
      pinkageParams: {
        consigneeProvinceId: '',
        pidList: []
      }, // 判断包邮
      postalMarketList: [
        '622901',
        '622921',
        '622922',
        '622923',
        '622924',
        '622925',
        '622926',
        '622927'
      ]
    }
  },
  /**
   * @param {Object} option
   * @param {String} option.id 订单oid
   * */
  onLoad(option) {
    this.pageQuery = option
    this.getOrderData()
    uni.$on(CHOOSE_RECEIVING_ADDRESS, this.chooseReceiving)
  },
  onUnload() {
    uni.$off(CHOOSE_RECEIVING_ADDRESS, this.chooseReceiving)
  },
  computed: {
    freightShow() {
      return '￥' + (this.freight ? this.freight.toFixed(2) : '0.00')
    }
  },
  methods: {
    toPosition(e) {
      // console.log(e, 'bindtapbindtapbindtapbindtap')
      // var that = this
      // uni.chooseLocation({
      //   success: function (lb) {},
      //   complete: function (lb) {
      //     that.detailedAddress = lb.name
      //     that.latitude = lb.latitude
      //     that.longitude = lb.longitude
      //     console.log(that.detailedAddress, '_++__+_++_++_+')
      //   },
      //   cancel: function (lb) {},
      //   fail: function (lb) {
      //     console.log(lb)
      //   }
      // })
    },
    showCoC() {
      this.show = true
    },
    selectCancel(v) {
      this.show = v
    },
    // 校验包邮
    async checkPinkage(v) {
      // 当前订单状态
      let nowStateArr = this.orderDetails.orderDetailVOList.map(
        (item) => item.state
      )
      console.log(nowStateArr)
      let nowState = ''
      if (nowStateArr.every((item) => item === 1)) {
        nowState = '包邮'
      } else {
        nowState = '付邮'
      }
      let areaCode = v || this.addressCode[2]

      let laterState = ''
      if (this.postalMarketList.includes(areaCode)) {
        if (areaCode == '622901') {
          this.freight = 8
        } else {
          this.freight = 12
        }
        laterState = '包邮'
      } else {
        this.getDetailsSuccess = false
        this.isPinkage = true
        laterState = '不配送'
      }

      if (this.status === -1) {
        if (laterState === '不配送') {
          // this.getDetailsSuccess = false
          // this.isPinkage = true
          this.flag = 1
          return 1
        } else {
          this.getDetailsSuccess = true
          this.isPinkage = false
          this.flag = 2
          return 2
        }
      } else if (this.status === 0) {
        if (laterState === '不配送') {
          // this.getDetailsSuccess = false
          // this.isPinkage = true
          this.flag = 1
          return 1
        } else if (nowState === '包邮' && laterState === '包邮') {
          this.getDetailsSuccess = true
          this.isPinkage = false
          this.flag = 2
          return 2
        } else {
          if (
            this.pinkageParams.consigneeProvinceId ===
            this.orderDetails.consigneeProvinceId
          ) {
            this.flag = 2
            return 2
          }
          this.flag = 3
          return 3
        }
      }
      // let areaCode = v || this.addressCode[2]
      // if (areaCode.includes(this.postalMarketList)) {
      //   if (this.addressCode[2] == '622901') {
      //     this.freight = 8
      //   } else {
      //     this.freight = 12
      //   }
      // } else {
      //   this.getDetailsSuccess = false
      //   this.isPinkage = true
      // }
      // 当前订单状态
      // let nowStateArr = this.orderDetails.orderDetailVOList.map(
      //   (item) => item.state
      // )
      // console.log(nowStateArr)
      // let nowState = ''
      // if (nowStateArr.every((item) => item === 1)) {
      //   nowState = '包邮'
      // } else {
      //   nowState = '付邮'
      // }
    },
    getOrderData() {
      uni.showLoading({
        mask: true
      })
      apiOrderDetails({
        id: this.pageQuery.id
      })
        .then((res) => {
          let { state, data, msg } = res.data
          console.log('*************', data)
          if (state === 'OK') {
            data.orderDetailVOList.forEach((item) => {
              if (item.state === 3) {
                this.isFreight = false
              }
            })
            this.orderDetails = data
            this.status = data.status
            data.orderDetailVOList.forEach((item) => {
              this.pinkageParams.pidList.push({
                num: item.num,
                pid: item.productVO.pid,
                sku: item.productVO.sku,
                price: item.orderPrice * item.num
              })
            })
            this.freight = data.freight
            // this.cartOrderData = data.orderDetailVOList;
            this.consignee = data.consigneeName
            this.receivingPhone = data.consigneePhone
            this.detailedAddress = data.consigneeAddress
            this.remark = data.remark
            this.addressValue = [
              data.consigneeProvinceId,
              data.consigneeCityId,
              data.consigneeCountyId
            ]
            this.regionStr = `${data.consigneeProvince}-${data.consigneeCity}-${data.consigneeCounty}`
            this.addressCode = [
              data.consigneeProvinceId,
              data.consigneeCityId,
              data.consigneeCountyId
            ]
            this.getDetailsSuccess = true
            uni.hideLoading()
          } else {
            uni.hideLoading()
            this.$am_toast.warning(msg)
          }
        })
        .catch((err) => {
          uni.hideLoading()
          this.$am_toast.error('查询失败，请重新尝试！')
        })
    },

    regionChange(e) {
      this.regionStr = e.detail.value.join('')
    },
    async addressPickerChange(e) {
      console.log(e)
      if (!e.data) {
        this.show = false
      }
      this.pinkageParams.consigneeProvinceId = e.code[0] // 设置包邮参数
      let flag = await this.checkPinkage(e.code[2])
      if (flag === 3 || flag === 1) {
        this.modalShow = true
        return
      }
      this.regionStr = e.name.join('-')
      this.addressCode = e.code
    },
    // 选择了收货地址
    async chooseReceiving(p_data) {
      console.log('用户选择地址后回调', p_data)
      this.pinkageParams.consigneeProvinceId = p_data.consigneeProvinceId // 设置包邮参数
      let flag = await this.checkPinkage(p_data.consigneeCountyId)
      if (flag === 3 || flag === 1) {
        this.modalShow = true
        return
      }
      this.consignee = p_data.consigneeName
      this.receivingPhone = p_data.consigneePhone
      this.detailedAddress = p_data.consigneeAddress
      this.addressValue = [
        p_data.consigneeProvinceId,
        p_data.consigneeCityId,
        p_data.consigneeCountyId
      ]
      this.regionStr = `${p_data.consigneeProvince}-${p_data.consigneeCity}-${p_data.consigneeCounty}`
      this.addressCode = [
        p_data.consigneeProvinceId,
        p_data.consigneeCityId,
        p_data.consigneeCountyId
      ]
    },
    // 点击去选择客户地址
    chooseCustomer() {
      this.$u.route('/pages/customer/customer-list', {
        pType: 'choose'
      })
    },
    // 提交订单
    submitOrder() {
      if (this.submitOrderLoading) return
      if (!this.consignee) {
        this.$am_toast('请输入收货人名称')
        return
      } else if (this.receivingPhone.length < 11) {
        this.$am_toast('收货电话格式不正确')
        return
      } else if (this.addressCode.length !== 3) {
        this.$am_toast('请选择省市区')
        return
      } else if (!this.detailedAddress) {
        this.$am_toast('请输入详细地址')
        return
      }
      this.submitOrderLoading = true
      this.updateOrder()
    },
    updateOrder() {
      uni.showLoading({
        mask: true
      })
      apiUpdateOrder({
        id: this.pageQuery.id,
        consigneeAddress: this.detailedAddress,
        consigneeRemarks: this.remark,
        consigneeCityId: this.addressCode[1],
        consigneeCountyId: this.addressCode[2],
        consigneeName: this.consignee,
        consigneePhone: this.receivingPhone,
        consigneeProvinceId: this.addressCode[0],
        freight: this.freight
      })
        .then((res) => {
          let { state, msg, data } = res.data
          uni.hideLoading()
          if (state === 'OK') {
            uni.$emit(UPDATE_ORDER_DETAILS, {
              id: this.pageQuery.id
            })
            uni.navigateBack({
              delta: 1
            })
          } else {
            this.$am_toast.warning(msg)
          }
          this.submitOrderLoading = false
        })
        .catch((err) => {
          console.log(err)
          uni.hideLoading()
          this.$am_toast.warning('操作失败，请重新尝试！')
          this.submitOrderLoading = false
        })
    }
    // 地址识别
    // addressTextGet() {
    //   if (!this.receivingAddress) {
    //     this.$am_toast('请输入内容！')
    //     return
    //   }
    //   uni.showLoading({
    //     mask: true
    //   })
    //   apiAddressGet({
    //     str: this.receivingAddress
    //   })
    //     .then(async (res) => {
    //       let { state, msg, data } = res.data
    //       console.log('---------------', data)
    //       uni.hideLoading()
    //       if (state === 'OK') {
    //         this.pinkageParams.consigneeProvinceId = data.provinceNo
    //         let flag = await this.checkPinkage()
    //         if (flag === 3 || flag === 1) {
    //           this.modalShow = true
    //           return
    //         }
    //         this.consignee = data.name
    //         this.receivingPhone = data.phone
    //         this.detailedAddress = data.address
    //         this.remark = data.remark
    //         this.addressValue = [data.provinceNo, data.cityNo, data.areaNo]
    //         this.regionStr = `${data.provinceName}-${data.cityName}-${data.areaName}`
    //         this.addressCode = [data.provinceNo, data.cityNo, data.areaNo]
    //       } else {
    //         this.$am_toast.warning(msg)
    //       }
    //     })
    //     .catch(() => {
    //       uni.hideLoading()
    //       this.$am_toast.error('操作失败，请重新尝试！')
    //     })
    // }
  }
}
</script>

<style lang="scss" scoped>
$section-plr: 19rpx;

.page-top-place {
  height: 16rpx;
}

.page-content {
  margin: 0 16rpx 16rpx;
  background: #ffffff;
  border-radius: 16rpx;
}

.content-card-title {
  height: 80rpx;
  padding: 0 $section-plr;
  font-size: 36rpx;
  font-weight: 500;

  .tip {
    font-size: 24rpx;
    color: #999;
  }
}

.company-section {
  margin-left: $section-plr;
  margin-right: $section-plr;

  & + .company-section {
    margin-top: 15rpx;
    border-top: 1px solid #e8e8e8;
  }
}

.company-section-title {
  padding-top: 18rpx;
  font-size: 24rpx;
  color: #000000;
}

.products-wrap {
  padding: 30rpx $section-plr 0;
}

.goods-item {
  display: flex;
  align-items: stretch;
  padding: 15rpx 0;

  & + .goods-item {
    // margin-top: 30rpx;
  }
}

.goods-cover {
  overflow: hidden;
  width: 150rpx;
  height: 150rpx;
  flex-shrink: 0;
  border-radius: 8rpx;
}

.goods-cover-img {
}

.goods-con {
  display: flex;
  flex: 1;
  width: 0;
  margin-left: 22rpx;
  flex-direction: column;
  justify-content: space-between;
}

.goods-name-wrap {
}

.goods-name {
  font-size: 30rpx;
  line-height: 42rpx;
}

.goods-price {
  font-size: 32rpx;
  color: #f65301;
}

.goods-price-unit {
  font-size: 24rpx;
}

.goods-price-num {
  font-size: 24rpx;
  color: #666;
}

.receiving-address {
  position: relative;
  z-index: 10;
}

.receiving-address__btn {
  position: absolute;
  z-index: 30;
  right: 10%;
  bottom: 25rpx;
  width: 80%;
  height: 48rpx;
  line-height: 48rpx;
  text-align: center;
  background: linear-gradient(135deg, #7ce166 0%, #4bb019 100%);
  border-radius: 27rpx;
  font-size: 24rpx;
  color: #fff;
}

.receiving-address__btn-hover {
  opacity: 0.5;
}

.f-cell-item {
  display: flex;
  justify-content: flex-end;
}

.f-cell-text {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 26rpx 32rpx;
}

.f-cell-item-input {
  width: 500rpx;
}

.footer-bar {
  position: fixed;
  left: 0;
  bottom: 0;
  z-index: 400;
  width: 750rpx;
  height: 98rpx;
  padding: 0 32rpx;
  background-color: #fff;
}

.footer-bar-place {
  height: 98rpx;
}

.submit-button {
  height: 66rpx;
  width: 690rpx;
  line-height: 66rpx;
  padding: 0 40rpx;
  background: linear-gradient(129deg, #f79128 0%, #fe6507 100%);
  border-radius: 32rpx;
  font-size: 30rpx;
  color: #fff;
}

.submit-button-hover {
  opacity: 0.5;
}

.specStyle {
  margin-top: 10rpx;
  padding: 5rpx 10rpx;
  background: rgba(239, 239, 244, 0.5);
  color: #999999;
  border-radius: 4rpx;
  font-size: 22rpx;
}

.err-tip {
  margin-bottom: 10rpx;
  text-align: center;
  color: #f65300;
}
.disable-btn {
  background: #b3b3b3 !important;
  color: #fff !important;
}
/deep/ .u-drawer-content {
  z-index: 20078 !important;
}
/deep/ .u-mask-show {
  z-index: 20073 !important;
}
</style>
